import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../views/Layout.vue'
import { useAuthStore } from '@/stores/auth'

const routes = [
  {
    path: '/',
    component: Layout,
    meta: { requiresAuth: true },
    children: [
      // 客户路由
      {
        path: '',
        name: 'CustomerHome',
        component: () => import('../views/customer/Home.vue'),
        meta: { role: 'customer' }
      },
      {
        path: '/rooms',
        name: 'RoomList',
        component: () => import('../views/customer/RoomList.vue'),
        meta: { role: 'customer' }
      },
      {
        path: '/orders',
        name: 'CustomerOrders',
        component: () => import('../views/customer/Orders.vue'),
        meta: { role: 'customer' }
      },
      
      // 管理员路由
      {
        path: '/admin/rooms',
        name: 'AdminRooms',
        component: () => import('../views/admin/Rooms.vue'),
        meta: { role: 'admin' }
      },
      {
        path: '/admin/users',
        name: 'AdminUsers',
        component: () => import('../views/admin/Users.vue'),
        meta: { role: 'admin' }
      },
      
      // 员工路由
      {
        path: '/employee/rooms',
        name: 'EmployeeRooms',
        component: () => import('../views/employee/Rooms.vue'),
        meta: { role: 'employee' }
      },
      {
        path: '/employee/orders',
        name: 'EmployeeOrders',
        component: () => import('../views/employee/Orders.vue'),
        meta: { role: 'employee' }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/auth/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/auth/Register.vue'),
    meta: { requiresAuth: false }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  // 不需要认证的页面直接放行
  if (!to.meta.requiresAuth) {
    return next()
  }
  
  // 需要认证但未登录，跳转到登录页
  if (!authStore.isAuthenticated) {
    return next('/login')
  }
  
  // 检查用户角色权限
  if (to.meta.role && to.meta.role !== authStore.userType) {
    // 角色不匹配，根据用户类型重定向到默认页面\
    if (authStore.isAdmin) {
      return next('/admin/rooms')
    } else if (authStore.isEmployee) {
      return next('/employee/orders')
    } else {
      return next('/')
    }
  }
  
  // 其他情况正常放行
  next()
})

export default router